$(function() {
    var $prev_href,
        $backgr = false,
        $curr_href = document.location.href.substring(document.location.href.lastIndexOf('/')+1);
    //console.log($curr_href);

    window.addEventListener('resize', resize, false);
    window.removeEventListener('resize', resize, false);

    /*if($.isFunction(c_dots)) {
        console.log('yes');
    } else {
        console.log('no');
    }*/

    //form support for browsers not supporting placeholder
    $('input, textarea').placeholder();

    //hide birds #anim1 on all pages except quote.html (added below)
    $('#anim1').hide();

    //workaround to add Competition Crushers submenu
    $('.cc_submenu').trigger('mouseenter').trigger('mouseleave');


    //ROTATING INDEX BACKGROUNDS
    var Banner = setInterval( "slideSwitch()", 9000 );
    //clearInterval(Banner); and then re-declare Banner


    /*for AJAX page reloading - OLD
     $('.sf-menu > li > a').click(function() {
     //console.log('works');
     if($(this).parent().hasClass('first')) {
     $('#tollfree').hide();
     $('#welcome').fadeIn(2300);
     } else {
     $('#tollfree').fadeIn(2300);
     $('#welcome').hide();
     }
     });*/

    //page updates sc1 : initial page loading
    switch($curr_href) {
        case 'index.html':
            $('#tollfree, .new_logo').hide();
            resize();
            window.addEventListener('resize', resize, false);
            break;

        case 'quote.html':
            $('#welcome').hide();
            $('.new_logo, #anim1').show();
            break;

        case '':
            $('#tollfree, .new_logo').hide();
            resize();
            window.addEventListener('resize', resize, false);
            break;

        default :
            $('#welcome').hide();
            $('.new_logo').show();
            break;
    }

        //page updates sc2 : AJAX subsequent page loading
    $(document).ajaxSuccess(function() {
        $prev_href = $curr_href;
        $curr_href = document.location.href.substring(document.location.href.lastIndexOf('/')+1);


        //check if AJAX relates to new page
        if($prev_href != $curr_href) {
            //console.log("Triggered ajaxSuccess handler: " + $curr_href);

            switch($curr_href) {

                case 'index.html':
                    $('#tollfree, .new_logo').hide();
                    $('#welcome').fadeIn(2300);
                    Banner = setInterval( "slideSwitch()", 9000 );
                    $backgr = $('#bgStretch div:eq(0)');
                    resize();
                    window.addEventListener('resize', resize, false);
                    break;

                case '':
                    $('#tollfree, .new_logo').hide();
                    $('#welcome').fadeIn(2300);
                    Banner = setInterval( "slideSwitch()", 9000 );
                    $backgr = $('#bgStretch div:eq(0)');
                    resize();
                    window.addEventListener('resize', resize, false);
                    break;

                case 'about.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(3)');
                    break;

                case 'competition_crushers.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(4)');
                    break;

                case 'quote.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(5)');
                    $('#anim1').show();
                    break;

                case 'image.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(6)');
                    break;

                case 'media.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(7)');
                    break;

                case 'partners.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(8)');
                    break;

                case 'privacy.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    //PRIVACY page custom scrollbar
                    $(".privacy_holder").mCustomScrollbar({
                        theme:"light-thick"
                    });
                    break;

                case 'tech.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(10)');
                    break;

                case 'demo_spokesmodels.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(10)');
                    break;

                case 'demo_patternlock.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    break;

                case 'thankyou.html':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    break;

                case 'demo_callme_button.php':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    break;

                case 'demo_sms.php':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    break;

                case 'demo_voice.php':
                    clearInterval(Banner);
                    $backgr = $('#bgStretch div:eq(9)');
                    break;

                default :
                    $('#tollfree, .new_logo').hide();
                    $('#welcome').fadeIn(2300);
                    Banner = setInterval( "slideSwitch()", 9000 );
                    $backgr = $('#bgStretch div:eq(0)');
                    resize();
                    window.addEventListener('resize', resize, false);
                    break;
            }

            //one-off effects when exiting from index
            if($prev_href == '' || $prev_href == 'index.html') {
                $('#tollfree').css({'left' : '840px'}).show().animate({'left' : '420px'}, 1000, 'easeOutBack');
                $('.new_logo').show().animate('opacity', '1');
                $('#welcome').hide();
                unresize();
                window.removeEventListener('resize', resize, false);
            }

            //one-off effects when exiting from competition crushers
            if($prev_href == 'competition_crushers.html' || $prev_href == 'tech.html' || $prev_href == 'media.html' || $prev_href == 'image.html') {
                $('.cc_submenu').trigger('mouseleave');
            }

            //one-off effects when exiting from quote
            if($prev_href == 'quote.html') {
                $('#anim1').hide();
            }

            //remove current backgrounds
            $('#bgStretch div').removeClass('last-active');
            $('.b_normal.active, .rotate.active').addClass(' last-active');
            $('#bgStretch div').removeClass('active');

            //add background
            $backgr.css('opacity', '0').animate({'opacity' : '1'}, 2400).addClass(' active');

        }
    });


});


//INDEX background slideshow
function slideSwitch() {
    var $b_active = $('#bgStretch div.rotate.active');
    $('#bgStretch div').removeClass('last-active');

    if ( $b_active.length == 0 ) $b_active = $('#bgStretch div.rotate:last');
    var $next = $b_active.next('.rotate').length ? $b_active.next('.rotate') : $('#bgStretch div.rotate:first');
    $b_active.addClass(' last-active');

    $next.css({ "opacity" : "0" })
        .addClass(' active')
        .animate({ "opacity" : "1" }, 3000, function() {
            $b_active.removeClass('active');
        });
}


//TECH and MEDIA slider functions
function c_slider(dir, p, tf) {
    $('.is_active').stop(true, true); //to fix 3 -> 1 dot problem
    var $dot, $c_next, $c_active = $('.is_active');

    if ( $c_active.length == 0 ) $c_active = $(p + ':first');

    if(dir == 'n') {
        $c_next = $c_active.next(p).length ? $c_active.next(p) : $(p + ':first');

        $c_active.stop(true).animate({left:'-1700px', right: '1700px'}, {duration:500, easing: "easeInCirc", queue: false}); //previous
        $c_next.css({left:'1700px', right:'-1700px'})
            .addClass(' is_active')
            .stop(true).delay(150)
            .animate({left:0, right:0},  {duration:500, easing: "easeOutCirc", queue: tf, complete:function() {
                $c_active.removeClass('is_active');
            }
            });

    } else {
        $c_next = $c_active.prev(p).length ? $c_active.prev(p) : $(p + ':last');
        //console.log($c_next.index() + ' first check ');

        $c_active.stop(true).animate({left:'1700px', right: '-1700px'}, {duration:500, easing: "easeInCirc", queue: false}); //previous
        $c_next.css({left:'-1700px', right:'1700px'})
            .addClass(' is_active')
            .stop(true).delay(150)
            .animate({left:0, right:0},  {duration:500, easing: "easeOutCirc", queue: tf, complete:function() {
                $c_active.removeClass('is_active');
            }
            });
    }

    //change dots at bottom
    $dot = $c_next.index() - 1;
    //console.log($c_next.index() + ' dot: ' + $dot);
        $('.media_nav > ul > li > a > img, .tech_nav > ul > li > a > img').attr('src', 'img/dot_not_selected.png');
        $('.media_nav > ul > li:eq(' + $dot + ') > a > img, .tech_nav > ul > li:eq(' + $dot + ') > a > img').attr('src', 'img/dot_selected.png');

    //reset demo_spokespersons .swf
    $('.talkinghead').find('object').remove();
    $('.container_models > a').show();
}


//TECH and MEDIA dots animations
function c_dots(i, p, tf) {
    var $c_dot = i - $('.is_active').index();
    //console.log(i + ' dot: ' + $('.is_active').index());
    switch ($c_dot) {
        case -5:
            c_slider('', p, tf); //wait for animation to complete (queue = false)
            c_slider('', p, tf);
            c_slider('', p, tf);
            c_slider('', p, tf);
            c_slider('', p, true);
            break;
        case -4:
            c_slider('', p, tf);
            c_slider('', p, tf);
            c_slider('', p, tf);
            c_slider('', p, true);
            break;
        case -3:
            c_slider('', p, tf);
            c_slider('', p, tf);
            c_slider('', p, true);
            break;
        case -2:
            c_slider('', p, tf);
            c_slider('', p, true);
            break;
        case -1:
            c_slider('', p, true);
            break;
        case 1:
            c_slider('n', p, true);
            break;
        case 2:
            c_slider('n', p, tf);
            c_slider('n', p, true);
            break;
        case 3:
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, true);
            break;
        case 4:
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, true);
            break;
        case 5:
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, tf);
            c_slider('n', p, true);
            break;
        default:
            break;
    }
}


//IMAGE page slider rotation
function c_image($c_next) {
    var $c_curr = $('.is_active');

    //console.log($c_curr.index() + ' next ' + $c_next);
    if($c_curr.index() != $c_next) {
        $c_next = $('.image_slide:eq(' + $c_next + ')');

        $c_curr.stop(true).animate({left:'-1700px', right: '1700px'}, {duration:500, easing: "easeInCirc", queue: false}); //previous
        $c_next.css({left:'1700px', right:'-1700px'})
            .addClass(' is_active')
            .stop(true).delay(150)
            .animate({left:0, right:0},  {duration:500, easing: "easeOutCirc", queue: true, complete:function() {
                $c_curr.removeClass('is_active');
            }
            });
    }
}


//update index page main menu position for media view
function resize() {
    if (window.matchMedia('only screen and (max-width: 1250px)').matches) {
        $('.main_menu').css({'marginLeft' : '-400px'});
    }
}

//reset js media queries when exiting index
function unresize() {
        $('.main_menu').css({'marginLeft' : ''});
}


//AJAX form submission - not used currently
function formAJAX() {
    $('#form1').submit(function(e) {
        var postData = $(this).serializeArray();
        var formURL = 'http://webspamprotect.com/wspform.php';
        $('.btns > span').show();
        $.ajax({
            url: formURL,
            type: "POST",
            data: postData,
            beforeSend:function() {

            },
            complete: function(data, textStatus, jqXHR) {              //success returns 404 for unknown reason
                //$('.quote_loading').hide();
                $('.success').html('Quote has been sent, we will contact you soon.')
                    .css({'opacity' : '0' ,'right': '-600px'})
                    .show()
                    .animate({'opacity' : '0.8', 'right': '15%'}, 1500, 'easeInQuint');
                //console.log('success');
             }
             /*,error: function(jqXHR, textStatus, errorThrown) {
             //if fails
                 console.log(jqXHR.status + ' ' + textStatus);
             }*/
         });
        e.preventDefault(); //STOP default action
    });

    $('#form1').submit(); //Submit the form
}

function d_show_model(n) {
    //console.log('show model: ' + n);
    var name;
    switch(n) {
        case 0:
            name = 'Baylee';
            break;
        case 1:
            name = 'Katie';
            break;
        case 2:
            name = 'Julia';
            break;
        case 3:
            name = 'Renny';
            break;
        case 4:
            name = 'Krystal';
            break;
        case 5:
            name = 'Maria';
            break;
        case 6:
            name = 'Joey';
            break;
        case 7:
            name = 'Derek';
            break;
        case 8:
            name = 'Jed';
            break;

        default:
            name = 'Baylee';
            break;
    }

    $('.container_models:eq(' + n + ') > a').fadeOut(1000);
    $('.talkinghead:eq(' + n + ')')
        .append('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/' +
            'pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="400" height="360"><param name="movie" ' +
            'value="demo_spokesmodels/images/demotest.swf" /><param name="wmode" value="transparent" /><param ' +
            'name="flashvars" value="vurl=' + name + '.flv" /><embed src="demo_spokesmodels/images/demotest.swf" width="400" ' +
            'height="360" wmode="transparent" flashvars="vurl=' + name + '.flv" pluginspage="http://www.macromedia.com/go/' +
            'getflashplayer"></embed></object>');
    setTimeout(function() {
        $('.talkinghead:eq(' + n + ')').find('object').remove();
        $('.container_models:eq(' + n + ') > a').fadeIn(1000);
    }, 29000);
}